﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

using Pixysoft.Framework.XSchEmA.Entity;

namespace Pixysoft.Framework.XSchEmA.Checker
{
    /// <summary>
    /// 多余节点
    /// 错误节点
    /// 不存在节点
    /// </summary>
    class TreeNodeChecker
    {
        private static TreeNodeChecker instance;
        public static TreeNodeChecker Instance
        {
            get
            {
                lock (typeof(TreeNodeChecker))
                {
                    if (instance == null)
                        instance = new TreeNodeChecker();
                    return instance;
                }
            }
        }

        const int TABLENODE = 2;

        public bool Check(TreeNode node, DatabaseSchema database)
        {
            List<string> list = new List<string>();
            Check(node, database, list);

            foreach (TableSchema table in database.Tables)
            {
                if (!list.Contains(table.TableName))
                    throw new Exception("不存在节点");
            }

            return true;
        }

        private bool Check(TreeNode node, DatabaseSchema database, List<string> list)
        {
            if (node.ImageIndex == TABLENODE && database.GetTable(node.Text) == null)
                throw new Exception("多余节点");

            if (node.ImageIndex == TABLENODE && list.Contains(node.Text))
                throw new Exception("重复节点");

            if (node.ImageIndex == TABLENODE && !list.Contains(node.Text))
                list.Add(node.Text);

            foreach (TreeNode leaf in node.Nodes)
                Check(leaf, database);

            return true;
        }
    }
}
